<!-- 用户列表 -->
<template>
  <div>
    <card>
      <el-form inline :model="listQuery" slot="header">
        <el-form-item label="用户名称：">
          <el-input clearable v-permission="$common.directiveButton(this, 'serach')" v-model="listQuery.username" placeholder="请输入用户名称" @keyup.enter.native="handleFilter">
            <el-button v-permission="$common.directiveButton(this, 'serach')" slot="append" icon="el-icon-search" @click="handleFilter"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button v-permission="$common.directiveButton(this, 'add')" type="primary" icon="el-icon-edit" @click="handleAddRole">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;">
        <el-table-column prop="userId" label="用户ID"></el-table-column>
        <el-table-column prop="name" label="用户姓名"></el-table-column>
        <el-table-column prop="username" label="用户账号"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter('map')">{{ row.status | statusFilter('name') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column align="center" label="操作" width="160">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope)">修改</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </card>
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改角色':'新增角色'" @close="$refs['ruleForm'].resetFields()">
      <el-form :model="user" :rules="rules" ref="ruleForm" label-width="80px" label-position="left" style="width:600px;margin-left: 50px;">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" placeholder="请输入角色姓名" />
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="user.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!user.userId">
          <el-input v-model="user.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="user.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIdList">
          <el-select style="width:100%" v-model="user.roleIdList" multiple filterable allow-create default-first-option placeholder="请选择角色标签">
            <el-option v-for="item in options" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model="user.status" label="0">禁用</el-radio>
          <el-radio v-model="user.status" label="1">正常</el-radio>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const defaultRole = {
  email: "",
  mobile: "",
  name: "",
  password: "",
  roleIdList: [],
  status: "1",
  username: "",
  // deptName: null,
  // deptId: null,
};

import Pagination from "@/components/Pagination";
import Card from '@/components/Card/index.vue'

// import { mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: 'user',
  // import引入的组件需要注入到对象中才能使用
  components: { Pagination, Card },
  filters: {
    statusFilter(status, type) {
      if (type == "map") {
        const statusMap = {
          1: "success",
          0: "info",
        };
        return statusMap[status];
      } else {
        const statusName = {
          1: "正常",
          0: "禁用",
        };
        return statusName[status];
      }
    },
  },
  data() {
    return {
      total: 0,
      listLoading: false,
      listQuery: {
        username: void 0,
        page: 1,
        limit: 10,
      },
      list: [],
      // 弹框
      dialogVisible: false,
      user: JSON.parse(JSON.stringify(defaultRole)),

      dialogType: "新增",

      options: [],

      rules: {
        name: [{ required: true, message: "请输入角色姓名", trigger: "blur" }],
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.$format.email(value)) {
                callback("请输入正确邮箱");
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.$format.mobile(value)) {
                callback("请输入正确手机号");
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        roleIdList: [
          { required: true, message: "请选择角色", trigger: "blur" },
        ],
        // status: [],
      },
    };
  },
  // 计算属性
  computed: {},
  // 监听属性
  watch: {},
  created() { },
  mounted() {
    this.getList();
    this.select();
  },
  methods: {
    // 所有角色
    // /sys/role/select
    select() {
      this.$http.get("/sys/role/select").then(({ list }) => {
        // dir(list)
        this.options = list;
      });
    },
    // 搜索
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    // 获取数据
    getList() {
      this.listLoading = true;
      this.$http.post("/sys/user/lists", this.listQuery).then((res) => {
        const { page } = res;
        this.total = page.totalCount;
        this.list = page.list;
        this.listLoading = false;
      });
    },
    // 新增角色
    handleAddRole() {
      // 滞空数据
      log(defaultRole);
      this.user = JSON.parse(JSON.stringify(defaultRole));
      this.dialogType = "新增";
      this.dialogVisible = true;
      // this.$refs['ruleForm'].resetFields()
    },
    // 修改角色
    handleEdit({ row }) {
      this.$http.get("/sys/user/info/" + row.userId).then((res) => {
        this.dialogType = "edit";
        this.dialogVisible = true;
        res.user.status += "";
        this.user = res.user;
      });
    },
    // 删除
    handleDelete({ row }) {
      this.$confirm("此操作不可逆转, 是否确定删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.post("/sys/user/delete", [row.userId + ""]).then((res) => {
            console.log(res);
            this.handleFilter();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 确认
    confirmRole() {
      log(this.user);

      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let url = "";
          if (this.user?.userId) {
            url = "/sys/user/update";
          } else {
            url = "/sys/user/save";
          }

          this.$http.post(url, this.user).then((res) => {
            log(res);
            this.dialogVisible = false;
            this.handleFilter();
          });
        }
      });
    },
  },
  beforeDestroy() { }, // 生命周期 - 销毁之前
};
</script>
<style lang='scss' scoped>
/* @import url(); 引入公共css类 */
</style>